﻿const url = require('url');
const queryString = require('querystring');
const logger = require('../logs/logger');
const config = require('../config');
const moment = require('moment');
const msgSvr = require('../svrs/msgSvr');

// privates 

function urldec(u) {
    return u.replace(/\\/g, '').replace(/amp;/g, '');
}

// privates 

module.exports = {
    msgsMap(msgs) {
        var maps = [];

        msgs.forEach((v, i, s) => {
            var comm = v.comm_msg_info;
            var ext = v.app_msg_ext_info;

            var decUrl = urldec(ext.content_url);
            var q = queryString.parse(url.parse(decUrl).query);

            if (q.__biz && q.mid && q.idx) {
                maps.push({
                    biz: q.__biz,
                    mid: q.mid,
                    idx: q.idx,
                    title: ext.title,
                    digest: ext.digest,
                    creation: comm.datetime * 1000,
                    src: decUrl,
                    covor: urldec(ext.cover),
                    author: ext.author,
                    updateAt: moment(new Date()).valueOf()
                });

                if (ext.is_multi) {
                    ext.multi_app_msg_item_list.forEach((sub, i, s) => {

                        decUrl = urldec(sub.content_url);
                        q = queryString.parse(url.parse(decUrl).query);

                        maps.push({
                            biz: q.__biz,
                            mid: q.mid,
                            idx: q.idx,
                            title: sub.title,
                            digest: sub.digest,
                            src: decUrl,
                            covor: urldec(ext.cover),
                            creation: comm.datetime * 1000,
                            author: sub.author,
                            updateAt: moment(new Date()).valueOf()
                        });
                    });
                }
            }
        });

        return maps;
    },

    async applyFetchOpt(subscription, msgs) {
        let days = await msgSvr.fetchOptions(subscription);
            const limits = moment().subtract(days, 'days').valueOf();

            var isContinue = days ?
                msgs.every((v, i, s) => v.creation >= limits) :
                true;

            var filteredMsgs = days ?
                msgs.filter((v, i, s) => v.creation >= limits) :
                msgs;

        return {
            isContinue,
            filteredMsgs
        };
    }
};